﻿using System;
using System.ComponentModel.Design;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using EnvDTE;

using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;

namespace HalconD
{
    /// <summary>
    /// Command handler
    /// </summary>
    internal sealed class RightCMD
    {
        /// <summary>
        /// Command ID.
        /// </summary>
        public const int CommandId = 0x0100;

        /// <summary>
        /// Command menu group (command set GUID).
        /// </summary>
        public static readonly Guid CommandSet = new Guid("a55b0d32-1c88-45e4-8b90-c958cc174960");

        public DTE dte;
        /// <summary>
        /// VS Package that provides this command, not null.
        /// </summary>
        private readonly AsyncPackage package;

        /// <summary>
        /// Initializes a new instance of the <see cref="RightCMD"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private RightCMD(AsyncPackage package, OleMenuCommandService commandService)
        {
            this.package = package ?? throw new ArgumentNullException(nameof(package));
            commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

            var menuCommandID = new CommandID(CommandSet, CommandId);
            var menuItem = new MenuCommand(this.Execute, menuCommandID);
            commandService.AddCommand(menuItem);
        }

        /// <summary>
        /// Gets the instance of the command.
        /// </summary>
        public static RightCMD Instance
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the service provider from the owner package.
        /// </summary>
        private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider
        {
            get
            {
                return this.package;
            }
        }

        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        public static async Task InitializeAsync(AsyncPackage package, DTE dte)
        {
            // Switch to the main thread - the call to AddCommand in RightCMD's constructor requires
            // the UI thread.
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);

            OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
            Instance = new RightCMD(package, commandService);
            Instance.dte = dte;


        }

        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
            //string title = "RightCMD";
            //DTE dte = (DTE)ServiceProvider.GetServiceAsync(typeof(DTE));


            if (dte.ActiveDocument != null && dte.Debugger.CurrentMode == dbgDebugMode.dbgBreakMode)
            {
                var selection = (TextSelection)dte.ActiveDocument.Selection;
                string text = selection.Text.Trim();
                //selection.WordLeft();

                //selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn);
                //int col = selection.ActivePoint.DisplayColumn;

                //selection.EndOfLine();
                //int col1 = selection.ActivePoint.DisplayColumn;

                ////var tmpstr=  text.Substring(col, col1 - col);

                ////EditPoint pt1 = (EditPoint)selection.ActivePoint.CreateEditPoint();

                // EditPoint pt2 = pt1.CreateEditPoint();
                string fileName = dte.ActiveDocument.FullName.ToLower();
                string expstring;
                if (fileName.EndsWith("cs"))
                {
                    expstring = "HalconAssit.HalAssit.Display" + "(" + text + "," + "\"" + text + "\"" + ")";
                }
                else
                {
                    //expstring = "T::add" + "(" + text + "," + text + ")";
                    expstring = "";

                }
                var express = dte.Debugger.GetExpression(expstring);
                if (express.IsValidValue)
                {

                }
                else
                {
                    MessageBox.Show($"计算异常 {express.Value}");
                }
            }
            else
            {
                MessageBox.Show("需要程序在Debug模式下,进入断点,才能使用此插件");
            }

        }
    }
}
